package cn.yitun.chat.yitunservermaincoresingle.main.business.chat.mq;

import cn.yitun.chat.yitunservercommonlib.dataentity.data.base.chat.ChatItem;
import cn.yitun.chat.yitunservercommonlib.dataentity.data.message.chat.Content;
import cn.yitun.chat.yitunserverimapicore.business.chat.service.GroupChatHistoryService;
import cn.yitun.chat.yitunserverimapicore.mq.GroupChatQueue;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.util.DaemonThreadFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * Description <br>
 * Date 2019-06-28 15:37:44<br>
 * 
 * @author yitun
 * @since 1.0.0
 */
@Component
public class GroupChatQueueImpl implements GroupChatQueue {

	@Resource
	GroupChatHistoryService groupChatHistoryService;

	GroupChatEventProducer producer;

	public GroupChatQueueImpl() {
		GroupChatEventFactory factory = new GroupChatEventFactory();
		int bufferSize = 1024 * 1024;
		Disruptor<GroupChatEvent> disruptor = new Disruptor<>(factory, bufferSize, DaemonThreadFactory.INSTANCE);
		disruptor.handleEventsWith((event, sequence, endOfBatch) -> on(event));
		disruptor.start();
		RingBuffer<GroupChatEvent> ringBuffer = disruptor.getRingBuffer();
		producer = new GroupChatEventProducer(ringBuffer);
	}

	private void on(GroupChatEvent event) {
		Content c = event.getContent();
		groupChatHistoryService.addGroupChatHistory(event.getGroupId(), event.getUserId(), c.getKey(), event.getChatItems());
	}

	@Override
	public void add(Long groupId, Long userId, Content content, List<ChatItem> chatItems) {
		producer.onData(groupId, userId, content, chatItems);
	}
}
